using Microsoft.AspNetCore.Mvc;
using RAG.Application.Dtos;
using RAG.Application.Interfaces;
using RAG.Application.Commands;
using RAG.Domain.Interfaces;
using Microsoft.AspNetCore.Authorization; // Added for Authorize attribute

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize] // 添加JWT认证
public class PermissionsController : ControllerBase
{
    private readonly IAppPermissionService _permissionService;
    private readonly IDomainEventPublisher _eventPublisher;

    public PermissionsController(
        IAppPermissionService permissionService,
        IDomainEventPublisher eventPublisher)
    {
        _permissionService = permissionService;
        _eventPublisher = eventPublisher;
    }

    /// <summary>
    /// 获取权限列表（分页）
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetPermissions(
        [FromQuery] int page = 1, 
        [FromQuery] int size = 10, 
        [FromQuery] string? search = null)
    {
        var result = await _permissionService.GetPermissionsAsync(page, size, search);
        return Ok(result);
    }

    /// <summary>
    /// 获取权限详情
    /// </summary>
    [HttpGet("{permissionId:guid}")]
    public async Task<IActionResult> GetPermission(Guid permissionId)
    {
        var result = await _permissionService.GetPermissionByIdAsync(permissionId);
        return Ok(result);
    }

    /// <summary>
    /// 创建权限
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> CreatePermission([FromBody] CreatePermissionDto dto)
    {
        var result = await _permissionService.CreatePermissionAsync(dto);
        return Ok(result);
    }

    /// <summary>
    /// 更新权限
    /// </summary>
    [HttpPut("{permissionId:guid}")]
    public async Task<IActionResult> UpdatePermission(Guid permissionId, [FromBody] UpdatePermissionDto dto)
    {
        var result = await _permissionService.UpdatePermissionAsync(permissionId, dto);
        return Ok(result);
    }

    /// <summary>
    /// 删除权限
    /// </summary>
    [HttpDelete("{permissionId:guid}")]
    public async Task<IActionResult> DeletePermission(Guid permissionId)
    {
        var result = await _permissionService.DeletePermissionAsync(permissionId);
        return Ok(result);
    }

    /// <summary>
    /// 启用权限
    /// </summary>
    [HttpPut("{permissionId:guid}/enable")]
    public async Task<IActionResult> EnablePermission(Guid permissionId)
    {
        var result = await _permissionService.EnablePermissionAsync(permissionId);
        return Ok(result);
    }

    /// <summary>
    /// 禁用权限
    /// </summary>
    [HttpPut("{permissionId:guid}/disable")]
    public async Task<IActionResult> DisablePermission(Guid permissionId)
    {
        var result = await _permissionService.DisablePermissionAsync(permissionId);
        return Ok(result);
    }
} 